package com.lollipop.ucenter.rpc.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lollipop.common.Pager;
import com.lollipop.common.service.CrudServiceImpl;
import com.lollipop.common.utils.EncryptUtils;
import com.lollipop.ucenter.rpc.api.UserService;
import com.lollipop.ucenter.rpc.model.User;
import com.lollipop.ucenter.rpc.repository.UserDao;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service("userService")
@Slf4j
public class UserServiceImpl extends CrudServiceImpl<UserDao, User> implements UserService {

    @Override
    public User findByUsername(String username) {
        User args = new User();
        args.setUsername(username);
        List<User> users = dao.findList(args);
        return CollectionUtils.isEmpty(users) ? null : users.get(0);
    }

    @Override
    public Set<String> findUserPermissions(String userId) {
        Set<String> pers = dao.findPermissions(userId);
        if (log.isDebugEnabled())
            log.debug(">>>> userId {} has permission {} ", userId, pers);
        Set<String> newPers = new HashSet<>();
        for (String per : pers) {
            if (!StringUtils.contains(per, ":")) {
                per += ":view";
            }
            newPers.add(per);
        }
        if (log.isDebugEnabled())
            log.debug(">>>> userId {} has newPermission {} ", userId, newPers);
        return newPers;
    }

    @Override
    @Transactional
    public boolean updatePassword(User user) {
        String newPassword = EncryptUtils.entryptPassword(user.getPassword(), EncryptUtils.generateSalt());
        user.setPassword(newPassword);
        dao.update(user);
        return true;
    }

}
